package com.softcomputer.rpt.ejb;

import com.softcomputer.rpt.entity.LogMessage;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
@LocalBean
public class UserSession {

    @Resource(mappedName = "jms/NotificationQueue")
    private Queue notificationQueue;
    @Resource(mappedName = "jms/NotificationQueueFactory")
    private ConnectionFactory notificationQueueFactory;
    @PersistenceContext(unitName = "Exchanger")
    private EntityManager em;
    private LogMessage message;

    public void persist(Object object) {
        message = (LogMessage) object;
        em.persist(message);
    }

    public List<LogMessage> retrieve() {
        Query getAllMessagesQuery = em.createNamedQuery("LogMessage.findAll");
        return getAllMessagesQuery.getResultList();
    }

    public LogMessage update(LogMessage logMessage) throws JMSException {
        LogMessage updatedMessage = em.merge(logMessage);
        sendJMSMessageToNotificationQueue(updatedMessage);
        return updatedMessage;
    }

    private Message createJMSMessageForjmsNotificationQueue(Session session, Object messageData) throws JMSException {
        TextMessage tm = session.createTextMessage();
        tm.setText(messageData.toString());
        return tm;
    }

    private void sendJMSMessageToNotificationQueue(Object messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = notificationQueueFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(notificationQueue);
            messageProducer.send(createJMSMessageForjmsNotificationQueue(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
